/*******************************************************************************
 * Copyright（C） CETC-32
 * @file:CookieUtil.java
 * @Description：
 * @Author ：徐文远
 * @version：1.0
 * @date ： 2021/2/2 下午2:03
 ******************************************************************************/

package com.cetc32.webutil.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CookieUtil
{
    /***
     * 获得cookie中的值 默认为 域名.com/cn
     * @param request
     * @param cookieName
     * @param isDecoder
     * @return
     */
    private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);
    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookieName == null){
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals(cookieName)) {
                    if (isDecoder) {//如果涉及中文
                        retValue = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                    } else {
                        retValue = cookies[i].getValue();
                    }
                    break;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }
    /***
     * 设置cookie的值
     * @param request
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param cookieMaxage
     * @param isEncode
     */
    public static  void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
        try {
            if (cookieValue == null) {
                cookieValue = "";
            } else if (isEncode) {
                cookieValue = URLEncoder.encode(cookieValue, "utf-8");
            }
            Cookie cookie = new Cookie(cookieName, cookieValue);
            if (cookieMaxage >= 0)
                cookie.setMaxAge(cookieMaxage);
            if (null != request)// 设置域名的cookie
                cookie.setDomain(getDomainName(request));
            // 在域名的根路径下保存
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /***
     * 获得cookie的主域名，保存时使用
     * @param request
     * @return
     */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName = null;
        String serverName = request.getRequestURL().toString();
        if (serverName == null || serverName.equals("") ) {
            domainName = "";
        } else if(isIp(serverName)){
            domainName = serverName;
        }else {
            serverName = serverName.toLowerCase();
            serverName = serverName.substring(serverName.indexOf("//")+2);
            logger.debug("serverName: {}",serverName);

            final int end = serverName.indexOf("/");
            serverName = serverName.substring(0, end);
            if(serverName.contains(":"))
                serverName= serverName.split("\\:")[0];
            logger.debug("serverName: {}",serverName);
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if(isIp(serverName)){
                domainName =serverName;
            }else if (len > 3) {
                // www.xxx.com.cn
                domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
            } else if (len <= 3 && len > 1) {
                // xxx.com or xxx.cn
                domainName = domains[len - 2] + "." + domains[len - 1];
            } else {
                domainName = serverName;
            }
        }
       /* if (domainName != null && domainName.indexOf(":") > 0) {
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }*/
        logger.debug("domainName = " + domainName);
        return domainName;
    }
    public boolean isCorrectIp2(String ipString) {
        String ipRegex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
        //IP地址的正则表达式
        //如果前三项判断都满足，就判断每段数字是否都位于0-255之间
        if(ipString.matches(ipRegex)){
            String[] ipArray = ipString.split("\\.");
            for (int i = 0; i < ipArray.length;i++){
                int number= Integer.parseInt(ipArray[i]);
                //4.判断每段数字是否都在0-255之间
                if (number <0 ||number>255) {
                return false;
                }
            }
		    return true;
        }else{
            return false;//如果与正则表达式不匹配，则返回false
        }
    }


    /***
     * 将cookie中的内容按照key删除
     * @param request
     * @param response
     * @param cookieName
     */
    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        setCookie(request, response, cookieName, null, 0, false);
    }
    /***************************************************
     * @param ip ip字符串
     * @return 返回是否为ip
     * **/
    public  static boolean isIp(String ip){
        String patternString = "(([0,1]?\\d?\\d|2[0-4]\\d|25[0-5])\\.){3}([0,1]?\\d?\\d|2[0-4]\\d|25[0-5])";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }
}
